<template>
  <div class="duty-schedule-wrap">
    <el-row type="flex" justify="space-between">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" @submit.native.prevent>
        <el-form-item v-if="$store.state.userinfo.isMuilUnitUser === 1">
          <el-select filterable v-model="searchForm.orgIds" placeholder="请选择业主单位">
            <el-option label="全部业主单位" :value="$store.state.userinfo.organizationIds"></el-option>
            <el-option
              v-for="item in orgOptions"
              :key="item.organizationId"
              :label="item.shortName"
              :value="item.organizationId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="searchForm.time"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="utils.intTimePickerOptions()"
            @change="getTable(1)">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item v-if="showClasses">
          <el-select filterable @change="getTable(1)" v-model="searchForm.watchClassId">
            <el-option label="请选择班次" value="-1"></el-option>
            <el-option
              v-for="item in classesOptions"
              :key="item.id"
              :label="item.orderName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-select filterable clearable @change="getTable(1)" v-model="searchForm.watchAccount" placeholder="请选择值班人员">
            <el-option label="全部值班人员" value=""></el-option>
            <el-option
              v-for="item in personnelOptions"
              :key="item.accountName"
              :label="item.name"
              :value="item.accountName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button class="form-search-btn" type="primary" @click="getTable(1)">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="more-btns">
        <el-dropdown @command="handleCommand" v-if="$store.state.buttonPermission[$store.state.currentTabName].indexOf('watchManager') > -1">
          <span class="el-dropdown-link">
            更多操作<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-if="showClasses" command="setClasses">设置班次</el-dropdown-item>
            <el-dropdown-item v-if="showClasses" command="addManully">手动添加</el-dropdown-item>
            <el-dropdown-item v-if="showClasses" command="autoGenerated">自动生成</el-dropdown-item>
            <el-dropdown-item command="batchDeletion">批量删除</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </el-row>
    <div>
      <el-table
        v-loading="loading"
        ref="dutyScheduleTableList"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" v-if="$store.state.buttonPermission[$store.state.currentTabName].indexOf('watchManager') > -1"></el-table-column>
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column label="日期" prop="watchDate" :formatter="formatWatchDate"></el-table-column>
        <el-table-column label="班次" prop="watchClassName"></el-table-column>
        <el-table-column label="上班时间" prop="watchStartTime" :formatter="formatDateTime"></el-table-column>
        <el-table-column label="下班时间" prop="watchEndTime" :formatter="formatDateTime"></el-table-column>
        <el-table-column label="值班人员" prop="watchAccountName"></el-table-column>
        <el-table-column label="操作" width="150" v-if="$store.state.buttonPermission[$store.state.currentTabName].indexOf('watchManager') > -1">
          <template slot-scope="scope" v-if="scope.row.watchDate > utils.ilinkTimeformat.format(new Date(), 'yyyyMMdd')">
            <!-- <el-button @click="editDutySchedule(scope.row)" type="text" size="small">编辑</el-button> -->
            <!-- <span class="dividing-line">|</span> -->
            <el-button @click="deleteDutySchedule(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-sizes="[10, 50, 100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!-- 班次设置弹框 -->
      <el-dialog
        :close-on-click-modal="false"
        title="班次设置"
        width="800px"
        top='10vh'
        v-if="dialogClassesSetting"
        :visible.sync="dialogClassesSetting"
        @close="closeClassesSetting"
        v-dialogDrag>
        <classes-setting :organizationId="searchForm.orgIds" :closeFun="closeClassesSetting"></classes-setting>
      </el-dialog>
      <!-- 手动添加值班表弹框 -->
      <el-dialog
        :close-on-click-modal="false"
        title="手动添加值班表"
        width="600px"
        top='10vh'
        v-if="dialogManualAddWatch"
        :visible.sync="dialogManualAddWatch"
        @close="closeManualAddWatch"
        v-dialogDrag>
        <manual-add-watch :organizationId="searchForm.orgIds" :closeFun="closeManualAddWatch"></manual-add-watch>
      </el-dialog>
      <!-- 自动生成值班表弹框 -->
      <el-dialog
        :close-on-click-modal="false"
        title="自动生成值班表"
        width="600px"
        top='10vh'
        v-if="dialogAutoCreatWatch"
        :visible.sync="dialogAutoCreatWatch"
        @close="closeAutoCreatWatch"
        v-dialogDrag>
        <auto-creat-watch :organizationId="searchForm.orgIds" :closeFun="closeAutoCreatWatch" :classesInfo="classesOptions" :userList="personnelOptions"></auto-creat-watch>
      </el-dialog>
      <!-- 编辑单个值班弹框 -->
      <el-dialog
        :close-on-click-modal="false"
        title="编辑值班情况"
        width="600px"
        top='10vh'
        v-if="dialogEditWatch"
        :visible.sync="dialogEditWatch"
        @close="closeEditWatch"
        v-dialogDrag>
        <edit-watch-form :organizationId="searchForm.orgIds" :closeFun="closeEditWatch" :oldInfo="curretEditWatchInfo" :classesInfo="classesOptions" :userList="personnelOptions"></edit-watch-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import utils from '@/utils/util'
import { getOrgList } from '@/api/org'
import {getUsers} from '@/api/api'
import * as Dao from '@/api/watch'
import classesSetting from './Dialog/ClassesSetting'
import manualAddWatch from './Dialog/ManualAddWatch'
import autoCreatWatch from './Dialog/AutoCreatWatch'
import editWatchForm from './Dialog/EditWatchForm'

export default {
  name: 'DutySchedule',
  props:['param'],
  components: { 
    classesSetting,
    manualAddWatch,
    autoCreatWatch,
    editWatchForm
  },
  data () {
    return {
      loading: false,
      utils: utils,
      orgOptions: [],
      showClasses: false, // 是否显示值班表选项
      classesOptions: [], // 班次下拉框数据
      personnelOptions: [],
      searchForm: {
        orgIds: '', // 业主单位
        time: '', // 时间
        watchAccount: '', // 值班人
        watchClassId: '-1', // 班次
      },
      // 统计
      statistics: {
        total: 0,
        normal: 0,
        abnormal: 0
      },
      // 列表
      tableData: [],
      // 选中的行
      multipleSelection: [],
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 班次设置弹框
      dialogClassesSetting: false, 
      dialogManualAddWatch: false,
      dialogAutoCreatWatch: false,
      dialogEditWatch: false,
      curretEditWatchInfo: {} // 当前编辑的值班信息
    }
  },
  created:function() {
    let that = this
    // 绑定下拉框
    if(this.$store.state.userinfo.isMuilUnitUser === 1) {
      getOrgList({queryType: 0}).then(res => {
        that.orgOptions = res.data
        //that.searchForm.orgIds = that.orgOptions[0].organizationId
      })
      that.searchForm.orgIds = that.$store.state.userinfo.organizationIds
    } else {
      that.searchForm.orgIds = that.$store.state.userinfo.org.id
    }
  },
  methods: {
    // 获取班次下拉框数据
    getClassesOptions() {
      let that = this
      let parames = {
        organizationId: this.searchForm.orgIds,
        sort: 'orderTimes',
        order: 'asc',
        offset: 0,
        limit: 20,
      }
      Dao.getClasses(parames).then(res => {
        that.classesOptions = res.data
      })
    },
    // 获取值班人员下拉框数据
    getPersonnelOptions() {
      let that = this
      getUsers({
        orgIds: this.searchForm.orgIds,
        roleIds: '142,144,145,160', // 排除小微场所角色
        queryType: 0
      }).then(res => {
        that.personnelOptions = res.data
      })
    },
    // 获取列表数据
    getTable (pageIndex, pageSize) {
      let that = this
      that.loading = true
      if (pageIndex) {
        that.currentPage = pageIndex
      }
      if (pageSize) {
        that.pageSize = pageSize
      }
      let parames = {
        orgIds: that.searchForm.orgIds || this.$store.state.userinfo.organizationIds,
        startTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[0] + ' 00:00:00' : '',
        endTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[1] + ' 23:59:59' : '',
        watchClassId: that.searchForm.watchClassId || '',
        watchAccount: that.searchForm.watchAccount || '',
        pageSize: that.pageSize,
        pageIndex: that.currentPage - 1
      }
      Dao.getDetailsList(parames).then(res => {
        that.tableData = res.data
        that.total = res.total
        that.loading = false
      })
    },
    handleSizeChange(pageSize) {
      this.getTable(1, pageSize)
    },
    handleCurrentChange(currentPage) {
      this.getTable(currentPage)
    },
    // 多选框
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    formatDateTime: function(row, column, cellValue, index) {
      if(cellValue) {
        return utils.ilinkTimeformat.format(new Date(cellValue), 'hh:mm')
      }else {
        return '-'
      }
    },
    formatWatchDate: function(row, column, cellValue, index) {
      if(cellValue) {
        let date = String(cellValue)
        return date.slice(0, 4) + '-' + date.slice(4, 6) + '-' + date.slice(6, 9)
      }else {
        return '-'
      }
    },
    // 编辑
    editDutySchedule(row) {
      this.curretEditWatchInfo = row
      this.dialogEditWatch = true
    },
    closeEditWatch(flag) {
      this.dialogEditWatch = false
      if(typeof(flag) !== 'object' && flag) {
        this.getTable()
      }
    },
    // 删除
    deleteDutySchedule(row) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      let nowDate = utils.ilinkTimeformat.format(new Date(), 'yyyyMMdd')
      
      if(row) {
        if(row.watchDate > nowDate) {
          this.$confirm('确认删除该排班吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            roundButton: true
          }).then(() => {
            // 删除接口
            Dao.delDetails({
              ids: row.id.toString()
            }).then(res => {
              if(res.status === 200) {
                this.$message.success('删除成功')
                // 刷新
                this.getTable(1)
              }
            })
            // 阻止事件冒泡
            event.stopPropagation()
          }).catch(() => {

          })
        } else {
          this.$message.warning('只能删除今天以后的数据')
          return false
        }
      }
    },
    // 更多操作
    handleCommand(command) {
      let that = this

      switch (command) {
        case 'setClasses':
          that.setClasses()
          return false
        case 'addManully':
          that.addManully()
          return false
        case 'autoGenerated':
          that.autoGenerated()
          return false
        case 'batchDeletion':
          that.batchDeletion()
          return false
        default:
          return false
      }
    },
    // 设置班次
    setClasses() {
      this.dialogClassesSetting = true
    },
    closeClassesSetting() {
      this.dialogClassesSetting = false
      // 获取班次
      this.getClassesOptions()
    },
    // 手动添加
    addManully() {
      this.dialogManualAddWatch = true
    },
    closeManualAddWatch(flag) {
      this.dialogManualAddWatch = false
      if(typeof(flag) !== 'object' && flag) {
        this.getTable()
      }
    },
    // 自动生成
    autoGenerated() {
      this.dialogAutoCreatWatch = true
    },
    closeAutoCreatWatch(flag) {
      this.dialogAutoCreatWatch = false
      if(typeof(flag) !== 'object' && flag) {
        this.getTable()
      }
    },
    // 批量删除
    batchDeletion() {
      let ids = []
      let that = this
      let selectList = this.multipleSelection
      let nowDate = utils.ilinkTimeformat.format(new Date(), 'yyyyMMdd')
      if(selectList.length > 0) {
        for(var i=0,len=selectList.length; i < len; i++) {
          if(selectList[i].watchDate <= nowDate) {
            this.$message.warning('只能删除今天以后的数据')
            return false
          } else {
            ids.push(selectList[i].id)
          }
        }
        // 确认弹框
        this.$confirm('确认删除选中的班次吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          roundButton: true
        }).then(() => {
          // 删除接口
          Dao.delDetails({
            ids: ids.toString()
          }).then(res => {
            if(res.status === 200) {
              this.$message.success('删除成功')
              // 刷新
              that.getTable(1)
            }
          })
        }).catch(() => {

        })
      } else {
        this.$message.warning('请勾选你要删除的值班记录')
      }
    },
  },
  watch: {
    currentOrgIds(val, oldVal) {
      if(val !== oldVal) {
        // 获取班次
        if(String(val).indexOf(',') > -1) {
          this.showClasses = false
        } else {
          this.showClasses = true
          this.getClassesOptions()
        }
        this.searchForm.watchClassId = '-1'
        // 获取用户列表
        this.getPersonnelOptions()
        this.searchForm.watchAccount = ''
        this.getTable(1)
      }
    }
  },
  computed: {
    currentOrgIds() {
      return this.searchForm.orgIds
    }
  }
}
</script>
